package com.example.myone.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.myone.Entity.Article;
import com.example.myone.Entity.User;
import com.example.myone.Mapper.ArticleMapper;
import com.example.myone.Mapper.UserMapper;
import com.example.myone.R;
import com.example.myone.Util.ClickUtils;
import com.example.myone.Util.ImageUtils;

import java.util.Objects;

public class ArticleActivity extends AppCompatActivity {


    private TextView title, topTitle, author, authorDown, introduction, content, likeCount;
    private ImageView image, avatar, likeButton, bookButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.article_activity);
        initView();
        // 获取参数：文章Id
        Intent intent = getIntent();
        int articleId = intent.getIntExtra("article_id", -1);
        // 返回
        ImageView topBack = findViewById(R.id.top_back_button);
        topBack.setOnClickListener(v -> finish());
        if (articleId != -1) { // 文章存在
            Article article = ArticleMapper.getArticleById(getApplicationContext(), articleId);
            if (article != null) {
                // 顶部的渲染
                topTitle.setText(article.category);
                // 正文的渲染
                title.setText(article.title);
                author.setText(String.format("文 / %s", article.author));
                introduction.setText(article.introduction);
                content.setText(article.content);
                // 底部操作栏
                authorDown.setText(article.author);
                ImageUtils.setImageByBase64Str(this, image, article.cover);
                User authorUser = UserMapper.getUserById(this, article.authorId);
                ImageUtils.setImageByBase64Str(this, avatar, Objects.requireNonNull(authorUser).avatar);
                // 点击前往用户详情
                ClickUtils.setClickToOtherActivityWithIntExtra(
                        this, AuthorActivity.class, "author_id", article.authorId, avatar, authorDown);
                // 绑定点击事件
                ClickUtils.setupLikeButton(this, article, likeButton, likeCount);
                ClickUtils.setupBookButton(this, bookButton);
            }
        }
    }

    private void initView() {
        title = findViewById(R.id.title);
        topTitle = findViewById(R.id.top_title);
        author = findViewById(R.id.author);
        authorDown = findViewById(R.id.author_down);
        introduction = findViewById(R.id.introduction);
        content = findViewById(R.id.content);
        likeCount = findViewById(R.id.like_count);
        likeButton = findViewById(R.id.like_button);
        bookButton = findViewById(R.id.book_button);
        image = findViewById(R.id.cover);
        avatar = findViewById(R.id.avatar);
    }
}
